package com.pan.structual.flyweight.factory;

import com.pan.structual.flyweight.entiy.CharMyImage;
import com.pan.structual.flyweight.entiy.MyImage;
import com.pan.structual.flyweight.utils.XmlUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;

public class StringPictureFactory {

    HashMap<String, MyImage> charMap;

    {
        charMap = new HashMap<>();
    }


    protected MyImage createCharImage(String ch){
        if (ch.length()!=1){
            throw new RuntimeException("只能有一个字母");
        }
        if (charMap.containsKey(ch)) {
            return charMap.get(ch);
        }
        CharMyImage charImage = new CharMyImage(ch);
        charMap.put(ch,charImage);
        return charImage;
    }

    protected String[] getOneStrArr(String str){
        String[] resultArr = new String[str.length()];
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            resultArr[i] = String.valueOf(c);
        }
        return resultArr;
    }

    public Image getStrImage(String str){
        String[] oneStrArr = getOneStrArr(str);
        int chHeight = XmlUtils.INSTANCE.getPictureWidthAndHeight()[0];
        int chWidth = XmlUtils.INSTANCE.getPictureWidthAndHeight()[1];
        int strWidth = oneStrArr.length * chWidth;
        int strHeight = chHeight;

        BufferedImage resultImage = new BufferedImage(strWidth,strHeight,BufferedImage.TYPE_INT_RGB);
        Graphics2D showGraphics = resultImage.createGraphics();


        for (int i = 0; i < oneStrArr.length; i++) {
            String ch = oneStrArr[i];
            MyImage chMyImage = createCharImage(ch);
            showGraphics.drawImage(chMyImage.getImage(),i*chWidth,0,chWidth,chHeight,null);
        }
        showGraphics.dispose();

        return resultImage;
    }


}
